<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\index\model\MemberModel;


class IndexController extends Controller {
	
	//登陆
	public function login() {
		
		if(request()->isPost()){
			$param=input('post.');
			
			$where['mobile'] = $param['user_tel'];
			$where['password'] = md5_salt($param['user_password']);
			
			$user_info = db('member')->where($where)->find();
    		if($user_info){
    			if($user_info['status'] == 1){
    				session('info_user', $user_info);
					session("uid",$user_info['id']);
    				$this->success('登录成功','index/index');
    			}else{
    				$this->error('账号异常，已冻结!');
    			}
    		}else{
    			$this->error('用户名密码错误');
    		}
		}
		
		return $this->fetch();
	}
	//注册
	public function regist() {
		if(request()->isPost()){
			$result = check_sendcode($_POST['mobile'], $_POST['tel_code']);
			if($result != 1) {
				$this->error('短信验证码错误或过期');
			}
			$user_info = db('member')->where('mobile',$_POST['mobile'])->find();
			if($user_info){
				$this->error('该手机号码已经注册');
			}
			$_POST['password'] = md5_salt($_POST['password']);
			$_POST['add_time'] = now_time();
			
			if($_POST['pid']){
				
			}
			
			$user_model = new MemberModel();
			$result=$user_model->allowField(true)->save($_POST);
			if($result){
				$user_id = db('member')->getLastInsID();
				
				$user_info = db('member')->where('id',$user_id)->find();
				
				session('info_user',$user_info);
				session('uid',$user_info['id']);
				$this->success('注册成功','index/member/index');
			}
			$this->error('注册失败');
		}
		return $this->fetch();
	}
	
	/**
     * 退出登录
     */
    public function logout() {
        session(null);
        $this->success('退出成功', 'index/index/login');
    } 
    
	//找回密码
	public function retrun_pwd() {
		
		if(request()->isPost()){
			
			$user_info = db('member')->where('mobile',$_POST['mobile'])->find();
			if($user_info){
				$result = check_sendcode($_POST['mobile'], $_POST['tel_code']);
				if($result != 1) {
					$this->error('短信验证码错误或过期');
				}
				$_POST['password'] = md5_salt($_POST['new_pwd']);
				
				$result = db('member')->where('id', $user_info['id'])->update(['password'=>$_POST['password']]);
				if($result){
					$this->success('修改成功','index/member/index');
				}else{
					$this->error('修改失败');
				}
				
			}else{
				$this->error('该手机号码用户不存在');
			}
		}
		return $this->fetch();
	}
	
	
	//首页
	public function index() {
		//申购处理
		$this->compute_subscribe();
		
		$where['status']=2;
		$list=db("order")->where($where)->field("add_time,max(price) price")->group("add_time")->order("add_time desc")->limit(10)->select();
		$times=[];
		$prices=[];
		if($list){
			foreach($list as $l){
				$times[]=date('m-d',strtotime($l['add_time']));
				$prices[]=$l['price'];				
			}
		}
		$data=array('prices'=>$prices,"times"=>$times);
		 $this->assign('data',json_encode($data));
		
		//首页轮播图
		$ab_list =db('ad')->order('add_time desc')->limit(4)->select();
		$this->assign('ab_list',$ab_list); 
		 
		
		//获取公告
		$help_info = db('help')->order('id desc')->find();
		$help_info['content'] = html_entity_decode($help_info['content']);
		$this->assign('help_info',$help_info);
		
		return $this->fetch();
	}
	
	//产品详情
	public function market_show() {
		$goods=db("goods")->find(input("id"));
		$where['goods_id']=$goods["id"];
		$where['status']=1;
		$where['type']=1;
		$field=" avg(price) as price,goods_id";
		$orders=db("order")->where($where)->order("price desc ")->limit(100)->select();
		$g_t=db("order")->where($where)->whereTime('order_time', 'today')->field($field)->find();
		$g_y=db("order")->where($where)->whereTime('order_time', 'yesterday')->field($field)->find();
		$avg_y=$g_y['price']?$g_y['price']:$goods['price'];//昨日成交均价
		$avg_t=$g_t['price']?$g_t['price']:$goods['price'];//今日成交均价
		$z=number_format($avg_t,2)-number_format($avg_y,2);
		$m=$z!=0?number_format(abs($z)/$avg_y,2):0;
		$this->assign("avg_y",$avg_y);
		$this->assign("z",$z);
		$this->assign("m",$m);
		$this->assign("good",$goods);
		$this->assign("orders",$orders);
		return $this->fetch();
	}
	//买入
	public function buy(){
		$goods=db("goods")->where("status",2)->select();
		$this->assign("goods",$goods);
		return $this->fetch();
	}
	//卖出成交
	public function sell_order(){
		$order_id=input('order_id');
		$order=db('order')->find($order_id);
		if(!$order){
			return json(["code"=>400,"msg"=>"无效的订单！"]);
		}
		if($order['status']==2||$order['status']==3){
			return json(["code"=>400,"msg"=>"该笔订单已经被成交或撤单！"]);
		}
		$num=$order['num'];
		$price=$order['price'];
		$total=$num*$price;
		$where["user_id"]=session('uid');
		$where['goods_id']=$order['goods_id'];
		$gd=db("product")->where($where)->find();
		if($gd['nums']<$num){
			return json(["code"=>400,"msg"=>"您的商品库存不足无法成交"]);
		}
		Db::startTrans();
		$res=db('order')->where("id",$order_id)->update(["status"=>2]);
		if($res){
			$log_res=$this->add_log(session('uid'),$order['uid'],$order['id'],$order['price'],$order['num'],$order['goods_id']);
			if($log_res){
				$where_p['id']=$gd['id'];
				//库存表扣
				$p_res=db("product")->where($where_p)->setDec("selling",$num);
				if($p_res){
					//扣除用户资金
					$u_res=db('member')->where('id',$order['uid'])->setDec("frozen_money",$total);
					if($u_res){
						$ad_res=$this->add_ulog($order['uid'],"交易支出",$order_id,$total,2);
						//增加卖家资金
						$s_res=db('member')->where('id',$order['uid'])->setInc("money",$total);
						$ad_res=$this->add_ulog(session("uid"),"交易收入",$order_id,$total,1);
						if($s_res){
							Db::commit();
							return json(["code"=>200,"msg"=>"交易成功"]);
						}else{
							Db::rollback();
							return json(["code"=>401,"msg"=>"交易失败"]);
						}
					}else{
						Db::rollback();
						return json(["code"=>401,"msg"=>"交易失败"]);
					}
				}else{
					Db::rollback();
					return json(["code"=>404,"msg"=>"交易失败"]);
				}
				
			}else{
				Db::rollback();
				return json(["code"=>403,"msg"=>"交易失败"]);
			}
		}else{
			 Db::rollback();
			 return json(["code"=>402,"msg"=>"交易失败"]);
		}

		
	}
	//买入成交
	public function buy_order(){
		$order_id=input('order_id');
		$order=db('order')->find($order_id);
		if(!$order){
			return json(["code"=>400,"msg"=>"无效的订单！"]);
		}
		if($order['status']==2||$order['status']==3){
			return json(["code"=>400,"msg"=>"该笔订单已经被成交或撤单！"]);
		}
		$num=$order['num'];
		$price=$order['price'];
		$total=$num*$price;
		$user=db("member")->find(session("uid"));
		if($user['money']<$total){
			return json(["code"=>400,"msg"=>"用户余额不足请先充值！"]);
		}
		Db::startTrans();
		$res=db('order')->where("id",$order_id)->update(["status"=>2]);
		if($res){
			$log_res=$this->add_log($order['uid'],session('uid'),$order['id'],$order['price'],$order['num'],$order['goods_id']);
			if($log_res){
				$where_p['user_id']=$order['uid'];
				$where_p['goods_id']=$order['goods_id'];
				//库存表扣
				$p_res=db("product")->where($where_p)->setDec("selling",$num);
				if($p_res){
					//扣除用户资金
					$u_res=db('member')->where('id',session("uid"))->setDec("frozen_money",$total);
					if($u_res){
						$ad_res=$this->add_ulog(session("uid"),"交易支出",$order_id,$total,2);
						//增加卖家资金
						$s_res=db('member')->where('id',$order['uid'])->setInc("money",$total);
						$ad_res=$this->add_ulog($order['uid'],"交易收入",$order_id,$total,1);
						if($s_res){
							Db::commit();
							return json(["code"=>200,"msg"=>"交易成功"]);
						}else{
							Db::rollback();
							return json(["code"=>401,"msg"=>"交易失败"]);
						}
					}else{
						Db::rollback();
						return json(["code"=>401,"msg"=>"交易失败"]);
					}
				}else{
					Db::rollback();
					return json(["code"=>404,"msg"=>"交易失败"]);
				}
				
			}else{
				Db::rollback();
				return json(["code"=>403,"msg"=>"交易失败"]);
			}
		}else{
			 Db::rollback();
			 return json(["code"=>402,"msg"=>"交易失败"]);
		}

		
	}
	//卖出
	public function sell(){
		$goods=db("product")->where("user_id",session("uid"))->select();
		$this->assign("goods",$goods);
		return $this->fetch();
	}
	//进货
	public function stock() {
		
		$goods=db("goods")->where("status",2)->select();
		$this->assign("goods_list",$goods);
		
		
		$order_where['status'] = 1;
		if($goods){
			$order_where['goods_id'] = input('goods_id')?input('goods_id'):$goods[0]['id'];
		}
		
		if(input('goods_id')){
			$this->assign("goods_id",0);
		}else{
			$this->assign("goods_id",input('goods_id'));
		}
		
		//获取所有订单
		$order_list = db('order')->where($order_where)->order('add_time desc')->paginate(10); 
		$this->assign("order_list",$order_list);
		$this->assign("goods_id",input('goods_id'));
		
		
		return $this->fetch();
	}
	//获取买入卖出订单 
	public function get_bs(){
		$where['type']=input("type");
		$where['goods_id']=input("goods_id");
		$where['status']=1;
		$order=input("order");
		$orders=db('order')->where($where)->order("price $order ")->limit(100)->select();
		return json(["orders"=>$orders]);
	}
	public function send_msg(){
		
		if(request()->isPost()){
			$mobile = $_POST['mobile'];
			
			$template_id 		= 'SMS_25225071';	//注册
			$template_title 	= '用户注册';
			
			/*switch ($_POST['type'])
			{
			case 1:
			  $template_id 		= 'SMS_25225071';	//注册
			  $template_title 	= '用户注册';
			  break;  
			case 2:
			   $template_id = 'SMS_85460045';	//找回密码
			   $template_title 	= '找回密码';
			  break;
			default:
			   $template_id = 'SMS_85390045';	//修改资料
			   $template_title 	= '修改资料';
			}*/
			
			$code = rand(100000, 999999);
			$app_config = config('alidayu');
			$msg = sendsms($app_config['app_sign'],$mobile,$app_config['regist_id'],'code',$code);
			if($msg){
				return json(["code"=>200,"msg"=>'发送成功!']); 
			}else{
				return json(["code"=>408,"msg"=>"发送失败"]); 
			}
		}
	}
	//交易日志
	public function add_log($sell_id,$buy_id,$order_id,$price,$nums,$goods_id){
		$data['sell_id']=$sell_id;
		$data['buy_id']=$buy_id;
		$data['order_id']=$order_id;
		$data['price']=$price;
		$data['nums']=$nums;
		$data['goods_id']=$goods_id;
		$data['add_time']=now_time();
		$res=db('log')->insert($data);
		return $res;
	}
	//仓库
	public function ck(){
		$counts=0;//商品数
		$price=0;//总市值
		$yk=0;//盈亏
		$ky=0;//可用资金
		$list=[];
		if(session('uid')){
			$ky=session('info_user')['money'];
			$where["user_id"]=session('uid');
			$where['nums']=['>',0];
			$list=db("product")->where($where)->select();
			foreach($list as $k=>$p){
				$counts += $p['nums'];//仓库库存
				$price  += $p['price']*$p['nums'];//
				$o_w["status"]=2;
				$o_w['goods_id']=$p['goods_id'];
				$dt=db("order")->where($o_w)->field("avg(price) price ")->find();
				if($dt){
					$yk+=$dt['price']-$p['price'];
					$list[$k]['avg']=$dt['price'];//涨跌
					$list[$k]['zd']=$dt['price']-$p['price'];
				}else{
					$list[$k]['avg']=$p['price'];//涨跌
					$list[$k]['zd']=0;
				}
			}
		}
		
		$this->assign("ky",$ky);
		$this->assign("counts",$counts);
		$this->assign("price",$price);
		$this->assign("yk",$yk);
		$this->assign("list",$list);
		return $this->fetch();
	}
	//撤单
	function chedan(){
		$order_id=input("order_id");
		$where['uid']=session("uid");
		$where['id']=$order_id;
		$order=db('order')->where($where)->find();
		if(!$order){
			return json(["code"=>400,"msg"=>'撤单失败']);
		}elseif($order['status']==2||$order['status']==3){
			return json(["code"=>400,"msg"=>'撤单失败']);
		}
		$num=$order['num'];
		$price=$order['price'];
		$total=$num*$price;
		Db::startTrans();
		$res=db('order')->where($where)->update(["status"=>3]);
		if($res){
			$type=$order['type'];
			if($type==1){//买入撤单
				$sql=" update sp_member set money=money+$total,frozen_money=frozen_money-$total  where id= ".$order['uid'];
				$res=Db::execute($sql);
				if($res){
					$ad_res=$this->add_ulog($order['uid'],"撤单返回",$order_id,$total,1);
					Db::commit();
				}else{
					Db::rollback();
				}
			}elseif($type==2){//卖出撤单
				$sql=" update sp_product set nums=nums+$num,selling=selling-$num  where uid=".$order['uid']." and goods_id= ".$order['goods_id'];
				$res=Db::execute($sql);
				if($res){
					Db::commit();
				}else{
					Db::rollback();
				}
			}
			return json(["code"=>200,"msg"=>'操作成功']);
		}else{
			return json(["code"=>400,"msg"=>'操作失败']);
		}
	}
	//添加用户日志
	public function add_ulog($uid,$title,$order_id,$price,$type){
		$data['uid']=$uid;
		$data['title']=$title;
		$data['order_id']=$order_id;
		$data['num']=$price;
		$data['type']=$type;
		$res=db('money')->insert($data);
		return $res;
	}
	//卖出
	
	//卖出挂单
	public function guadan2(){
		$user=db("member")->find(session('uid'));
		$goods_id=input("goods_id");//进货商品
		$price=input("price");//进货价格
		$num=input("num");
		$where["goods_id"]=$goods_id;
		$where['user_id']=session("uid");
		$product=db('product')->where($where)->find();
		if($product){
			$mynum=$product['nums'];//我的库存
			$selling_num=$product['selling'];//当前出售中
			$sy=$mynum-$selling_num;//当前剩余库存
			if($sy<$num){
				return json(["code"=>400,"msg"=>"库存为".$sy."库存不足"]); 
			}
			Db::startTrans();
			$data['uid']=$user['id'];
			$data['price']=$price;
			$data['num']=$num;
			$data['type']=2;
			$data['add_time']=now_time();
			$data['goods_id']=$goods_id;
			$data['status']=1;
			$res=db('order')->insert($data);
			if($res){
				$sql=" update sp_product set nums=nums-$num,selling=selling+$num  where id= ".$product['id'];
				$res2=Db::execute($sql);
				if($res2){
					Db::commit();
					return json(["code"=>200,"msg"=>"挂单成功"]); 
				}else{
					Db::rollback();
					return json(["code"=>402,"msg"=>"挂单失败"]);
				}
				
			}else{
				return json(["code"=>400,"msg"=>"挂单失败"]); 
			}
			
		}else{
			return json(["code"=>408,"msg"=>"您的仓库无此商品!"]); 
		}
	}
	//挂单进货
	public function guadan(){
		$user=db("member")->find(session('uid'));
		$goods_id=input("goods_id");//进货商品
		$price=input("price");//进货价格
		$num=input("num");
		$total=$price*$num;
		if($user['money']<$total){
			return json(["code"=>408,"msg"=>"账户余额不足请先充值"]); 
		}else{
			$data['uid']=$user['id'];
			$data['price']=$price;
			$data['num']=$num;
			$data['type']=1;
			$data['add_time']=now_time();
			$data['goods_id']=$goods_id;
			$data['status']=1;
			$res=db('order')->insert($data);
			if($res){
				$sql=" update sp_member set money=money-$total,frozen_money=frozen_money+$total  where id= ".session("uid");
				Db::execute($sql);
				return json(["code"=>200,"msg"=>"挂单成功"]); 
			}else{
				return json(["code"=>400,"msg"=>"挂单失败"]); 
			}
		}
	}
	//市场
	public function market(){
		$where['status']=2;
		$field=" avg(price) as price,goods_id";
		$list_t=db("order")->where($where)->whereTime('order_time', 'today')->field($field)->group("goods_id")->buildSql();
		$list_y=db("order")->where($where)->whereTime('order_time', 'yesterday')->field($field)->group("goods_id")->buildSql();
		$field1="a.name,a.id,t.price as t,y.price as y";
		$list=db('goods')->alias('a')->field($field1)
		->join($list_t.'t','a.id = t.goods_id','left')
		->join($list_y.'y','a.id = y.goods_id','left')
		->where("a.status",2)->select();
		if($list){
			foreach($list as $k=>$v){
				$list[$k]['y']=number_format($list[$k]['y'],2);
				$list[$k]['t']=number_format($list[$k]['t'],2);
				$z=$list[$k]['t']>0?number_format($list[$k]['t'],2)-number_format($list[$k]['y'],2):"";
				$list[$k]['z']=$z;
				$m=$list[$k]['y']>0&&$z!=""?number_format(abs($z)/$list[$k]['y'],2):"";
				$list[$k]['m']=$m;
			}
		}
		$this->assign("list",$list);
		
		
		//市场广告
		$new_content = db('article')->order('add_time desc')->limit(1)->select();
		$this->assign("new_content",$new_content[0]);
		return $this->fetch();
	}
	
	 //产品结算
	function compute_subscribe(){
		$cut_time = date("Y-m-d H:i:s");
		
		//获取所以产品
		$goods_list = db('goods')->where('status',1)->select();
		for($i=0;$i<count($goods_list);$i++){
			$start_time = $goods_list[$i]['add_time'];
			$end_time = $goods_list[$i]['end_time'];
			// 启动事务
			try{
				//产品认筹结束
				if(strtotime($cut_time)>strtotime($end_time)){
					//产品改为发行
					db('goods')->where('id', $goods_list[$i]['id'])->update(['status' => 2]);
					
					$release['uid']			=1;
					$release['price']		=$goods_list[$i]['price'];
					$release['num']			=$goods_list[$i]['stock'];
					$release['type']		=2;
					$release['add_time']	=now_time();
					$release['goods_id']	=$goods_list[$i]['id'];
					$release['status']		=1;
					$cut_res=db('order')->insert($release);
					
					//查找认筹订单
					$subscribe_list = db('subscribe')
										->where('goods_id',$goods_list[$i]['id'])
										->where('state',1)
										->select();
					for($j=0;$j<count($subscribe_list);$j++){
						//认筹产品改为中签
						db('subscribe')->where('id', $subscribe_list[$j]['id'])->update(['state' => 2]);
						//查找认筹用户信息
						$user_info = db('member')->where('id',$subscribe_list[$j]['user_id'] )->find();
						//冻结金额
						$cut_frozen_money = bcsub($user_info['frozen_money'], $subscribe_list[$j]['frozen_money'], 2);
						//修改用户冻结金额
						db('member')->where('id', $subscribe_list[$j]['user_id'])->update(['frozen_money' => $cut_frozen_money]);
						//用户金额变化记录
						$this->add_ulog2($subscribe_list[$j]['user_id'],'中签',$subscribe_list[$j]['id'],$subscribe_list[$j]['frozen_money'],2);
						//就算申购用户上级用户
						$up_commission = bcmul($cut_frozen_money, 0.1, 2);
						
						//增加申购用户上级佣金
						db('member')->where('id', $subscribe_list[$j]['pid'])->update(['money' => $up_commission]);
						//用户金额变化记录
						$this->add_ulog2($subscribe_list[$j]['pid'],'推荐会员申购佣金',$subscribe_list[$j]['id'],$up_commission,1);
						
						//新增仓库
						$data['goods_name']	= $goods_list[$i]['name'];
						$data['goods_id']	= $goods_list[$i]['id'];
						$data['price']		= $goods_list[$i]['price'];
						$data['nums']		= $subscribe_list[$j]['buy_number'];
						$data['user_id']	= $subscribe_list[$j]['user_id'];
						$data['selling']	= 0;
						$data['add_time']	= now_time();;
						$res=db('product')->insert($data);
					}
				}
			} catch (\Exception $e) {
				// 回滚事务
				Db::rollback();
				//dump($e->getMessage());
				return json(["code"=>405,"msg"=>'数据异常']);
				exit;
			}
		}
	}
	
	//添加用户日志
	function add_ulog2($uid,$title,$order_id,$price,$type){
		$data['uid']=$uid;
		$data['title']=$title;
		$data['order_id']=$order_id;
		$data['num']=$price;
		$data['type']=$type;
		$res=db('money')->insert($data);
		return $res;
	}
	
	
	function stock_rule(){
		return $this->fetch();
	}
}
